package org.phalanx.zip;

import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.util.zip.Inflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipFileArchiveReader {
	private ZipFile zipFileArchive;
	private int byteSize;
	
	public ZipFileArchiveReader(){
	}
	
	public ZipFileArchiveReader(File file) throws IOException{
		this.setZipFile(file);
	}
	
	public ZipFileArchiveReader(String fileName) throws IOException{
		this.setZipFileByName(fileName);
	}
	
	public void setZipFile(File file) throws IOException{
		zipFileArchive = new ZipFile(file);
	}
	
	public void setZipFileByName(String fileName) throws IOException {
		zipFileArchive = new ZipFile(new File(fileName));
	}
	
	public boolean isFileExist(){
		boolean isExists = false;
		
		if (zipFileArchive != null){
			isExists = new File(zipFileArchive.getName()).exists();
		}
		
		return isExists;
	}
	
	public String getArchivedFileAsString(String archivedFile){
		String buffer = null;
		
		byte[] b = getArchivedFile(archivedFile);
		
		if (b.length > 0){
			buffer = new String(b);
		}
		
		try {
		zipFileArchive.close();
		} catch (IOException ie){}
		return buffer;
	}
	
	public byte[] getArchivedFile(String archivedFile){
		byte[] b = new byte[0];
		
		ZipEntry z = zipFileArchive.getEntry(archivedFile);

		try {
			if (z != null){
				byteSize = (int)z.getSize();
				
				b = new byte[byteSize];

				Inflater d = new Inflater();
				DataInputStream dOut = new DataInputStream(zipFileArchive.getInputStream(z));
				boolean hasMore = true;
				int startPos = 0;
				
				while(startPos != -1){
					startPos = dOut.read(b, startPos, b.length - startPos);
				}

				d.inflate(b);
				d.end();
			}
		} catch (Exception e){}

		return b;
	}
	
	public int getByteSize(){
		return byteSize;
	}
}
